package com.ruoyi.web.controller.rest.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.WebUser;
import com.ruoyi.system.domain.WebUserAddress;
import com.ruoyi.system.service.IWebUserAddressService;
import com.ruoyi.system.service.IWebUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 微信公众号菜单 信息操作处理
 *
 * @author liupan
 * @date 2019-03-25
 */
@Api(tags = "用户地址管理")
@RestController
@RequestMapping("/rest/user/address")
public class _UserAddressController extends BaseController {
    @Autowired
    private IWebUserAddressService iWebUserAddressService;
    @Autowired
    private IWebUserService iWebUserService;


    @ApiOperation(value = "我的收货地址", notes = "province:省，city：市，district：区，address：详细地址，user_name：联系人,mobile:电话，is_default：是否默认")
    @GetMapping()
    public AjaxResult getAddress(Integer userId) {
        if(userId == null){
            return error("userId不能为null");
        }
        WebUser userData = iWebUserService.getById(userId);
        if(userData == null){
            return error(Constants.REQUIRED_FAILD);
        }
        List<Map<String, Object>> news = iWebUserAddressService.listMaps(new QueryWrapper<WebUserAddress>()
                .eq("user_id", userId)
                .select("id", "province", "city", "district", "address","user_name","mobile","is_default","baseaddress","longitude","latitude")
                .orderByDesc("is_default","create_time"));

        return AjaxResult.success(news);
    }

    @ApiOperation(value = "用户默认地址", notes = "province:省，city：市，district：区，address：详细地址，user_name：联系人,mobile:电话，is_default：是否默认")
    @GetMapping("default")
    public AjaxResult getAddressDefault(Integer userId) {
        if(userId == null){
            return error("userId不能为null");
        }
        WebUser userData = iWebUserService.getById(userId);
        if(userData == null){
            return error(Constants.REQUIRED_FAILD);
        }
        Map<String, Object> data = iWebUserAddressService.getMap(new QueryWrapper<WebUserAddress>()
                .eq("user_id", userId)
                .eq("is_default","1")
                .select("id", "province", "city", "district", "address","user_name","mobile","is_default","baseaddress").orderByDesc("create_time"));

        return AjaxResult.success(data);
    }

    @ApiOperation(value = "保存收货地址", notes = "province:省，city：市，district：区，address：详细地址，" +
            "user_name：联系人,mobile:电话，is_default：是否默认,longitude:经度，latitude：纬度")
    @PostMapping("save")
    public AjaxResult saveAddress(@RequestBody WebUserAddress userAddress) {
        if(userAddress == null || userAddress.getUserId() == null){
            return error("userId不能为null");
        }
        if(StringUtils.isEmpty(userAddress.getLatitude())){
            return error("请使用定位功能确定地址");
        }
        if(StringUtils.isEmpty(userAddress.getLongitude())){
            return error("请使用定位功能确定地址");
        }
        WebUser userData = iWebUserService.getById(userAddress.getUserId());
        if(userData == null){
            return error(Constants.REQUIRED_FAILD);
        }
        userAddress.setUserId(userAddress.getUserId());

        //如果当前用户没有其他收货地址，则默认当条为默认地址
        int co = iWebUserAddressService.count(new QueryWrapper<WebUserAddress>().eq("user_id",userAddress.getUserId()));
        if(co == 0){
            userAddress.setIsDefault(1);
        }

        int count = iWebUserAddressService.count(new QueryWrapper<WebUserAddress>()
                .eq("province",userAddress.getProvince())
                .eq("city",userAddress.getCity())
                .eq("district",userAddress.getDistrict())
                .eq("address",userAddress.getAddress())
                .eq("mobile",userAddress.getMobile())
                .eq("user_name",userAddress.getUserName())
                .eq("user_id",userAddress.getUserId()));

        if(count> 0 ){
            return  error("此地址已存在");
        }
        if(userAddress.getIsDefault() == 1){
            iWebUserAddressService.update(new UpdateWrapper<WebUserAddress>().set("is_default",0).eq("user_id",userAddress.getUserId()));
        }
        iWebUserAddressService.saveOrUpdate(userAddress);
        Object data = userAddress.getBaseaddress();
        return AjaxResult.success(data);
    }

    @ApiOperation(value = "设为默认地址", notes = "")
    @PutMapping("default")
    public AjaxResult saveDefaultAddress(Integer userId , Integer addressId) {
        if(userId == null){
            return error("userId不能为null");
        }
        if(addressId == null){
            return error("addressId不能为null");
        }
        WebUser userData = iWebUserService.getById(userId);
        if(userData == null){
            return error(Constants.REQUIRED_FAILD);
        }
        WebUserAddress addressData = iWebUserAddressService.getById(addressId);
        if(addressData == null || !addressData.getUserId().equals(userData.getId())){
            return error(Constants.REQUIRED_FAILD);
        }
        iWebUserAddressService.update(new UpdateWrapper<WebUserAddress>().set("is_default",0).eq("user_id",userId));
        iWebUserAddressService.update(new UpdateWrapper<WebUserAddress>().set("is_default",1).eq("id",addressId));
        return AjaxResult.success();
    }

    @ApiOperation(value = "删除地址", notes = "")
    @DeleteMapping()
    public AjaxResult delete(Integer userId , Integer addressId) {
        if(userId == null){
            return error("userId不能为null");
        }
        if(addressId == null){
            return error("addressId不能为null");
        }
        WebUser userData = iWebUserService.getById(userId);
        if(userData == null){
            return error(Constants.REQUIRED_FAILD);
        }
        WebUserAddress addressData = iWebUserAddressService.getById(addressId);
        if(addressData == null || !addressData.getUserId().equals(userData.getId())){
            return error(Constants.REQUIRED_FAILD);
        }

        return AjaxResult.success(iWebUserAddressService.removeById(addressId));
    }
}
